# 工作流调度器管理命令
from django.core.management.base import BaseCommand
from django.utils import timezone
import logging
import time

from assets.workflow_scheduler import workflow_scheduler

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = '运行工作流调度器'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--interval',
            type=int,
            default=60,
            help='调度间隔（秒），默认60秒'
        )
        
        parser.add_argument(
            '--once',
            action='store_true',
            help='只运行一次，不循环'
        )
        
        parser.add_argument(
            '--task',
            choices=['scheduled', 'overdue', 'timer', 'cleanup', 'reports', 'all'],
            default='all',
            help='指定要执行的任务类型'
        )
    
    def handle(self, *args, **options):
        interval = options['interval']
        run_once = options['once']
        task_type = options['task']
        
        self.stdout.write(
            self.style.SUCCESS(f'启动工作流调度器，间隔: {interval}秒，任务类型: {task_type}')
        )
        
        try:
            while True:
                start_time = timezone.now()
                
                try:
                    if task_type in ['scheduled', 'all']:
                        self.stdout.write('处理计划工作流...')
                        workflow_scheduler.process_scheduled_workflows()
                    
                    if task_type in ['overdue', 'all']:
                        self.stdout.write('处理超时任务...')
                        workflow_scheduler.process_overdue_tasks()
                    
                    if task_type in ['timer', 'all']:
                        self.stdout.write('处理定时器任务...')
                        workflow_scheduler.process_timer_tasks()
                    
                    if task_type in ['cleanup', 'all']:
                        # 每小时执行一次清理
                        if start_time.minute == 0:
                            self.stdout.write('清理旧实例...')
                            workflow_scheduler.cleanup_old_instances()
                    
                    if task_type in ['reports', 'all']:
                        # 每天执行一次报告生成
                        if start_time.hour == 8 and start_time.minute == 0:
                            self.stdout.write('生成工作流报告...')
                            workflow_scheduler.generate_workflow_reports()
                    
                    execution_time = (timezone.now() - start_time).total_seconds()
                    self.stdout.write(
                        self.style.SUCCESS(f'调度完成，耗时: {execution_time:.2f}秒')
                    )
                    
                except Exception as e:
                    self.stdout.write(
                        self.style.ERROR(f'调度执行失败: {e}')
                    )
                    logger.error(f'工作流调度器执行失败: {e}')
                
                if run_once:
                    break
                
                # 等待下次执行
                time.sleep(interval)
                
        except KeyboardInterrupt:
            self.stdout.write(
                self.style.SUCCESS('工作流调度器已停止')
            )
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'工作流调度器异常退出: {e}')
            )
            logger.error(f'工作流调度器异常退出: {e}')